package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.context.UserHolder;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.BusinessException;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.mapper.UserMapper;
import com.sky.result.PageBean;
import com.sky.service.AddressBookService;
import com.sky.service.AppShoppingCartService;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.ws.WebSocketServer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
@RequiredArgsConstructor// lombok提供的，代替所有的@Autowired，要求被注入对象final关键字
@Transactional
public class OrderServiceImpl implements OrderService {

    private final AddressBookService addressBookService;

    private final AppShoppingCartService shoppingCartService;

    private final OrdersMapper ordersMapper;

    private final OrderDetailMapper orderDetailMapper;

    private final UserMapper userMapper;

    private final WeChatPayUtil weChatPayUtil;

    private final ShoppingCartMapper shoppingCartMapper;

    private final WebSocketServer webSocketServer;

    @Override
    public OrderSubmitVO save(Orders orders) {
        //1. 查询收货地址信息
        AddressBook addressBook = addressBookService.findById(orders.getAddressBookId());
        //2. 查询购物车信息
        List<ShoppingCart> shoppingCartList = shoppingCartService.findList();
        //3. 保存订单
        //3-1 补齐参数
        orders.setNumber(IdUtil.simpleUUID());// 32位随机字符串，作为订单号
        orders.setStatus(1);// 订单状态：待付款
        orders.setUserId(UserHolder.get());// 下单用户
        orders.setOrderTime(LocalDateTime.now());// 下单时间
        orders.setPayStatus(0);// 支付状态：未支付
        orders.setPhone(addressBook.getPhone());// 收货人手机号
        orders.setAddress(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());//收货地址
        orders.setConsignee(addressBook.getConsignee());// 收货人
        //3-2 mapper保存（主键返回）
        ordersMapper.save(orders);
        //4. 保存订单详情
        //4-1 遍历购物车
        shoppingCartList.stream().forEach(shoppingCart -> {
            //4-2. 拷贝购物项（忽略id属性）
            OrderDetail orderDetail = BeanUtil.copyProperties(shoppingCart, OrderDetail.class, "id");
            //4-3. 设置订单id
            orderDetail.setOrderId(orders.getId());
            //4-4 mapper保存
            orderDetailMapper.save(orderDetail);
        });
        //5. 清空购物车
        shoppingCartService.clean();
        //6. 封装并返回vo
        OrderSubmitVO vo = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount())
                .build();
        return vo;
    }

    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        User user = userMapper.findByUserId(UserHolder.get());

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new BusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }



    // 支付成功，修改订单状态
    public void paySuccess(String outTradeNo) {
        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.findByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)//2 订单状态 待接单
                .payStatus(Orders.PAID)//1支付状态 已支付
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);


        //===================================通知商家: 新订单来了===========================//
        //1. 准备消息内容
        Map<String,Object> map = new HashMap<>();
        map.put("type",1);
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号：" + ordersDB.getNumber());
        //2. 转json
        String json = JSON.toJSONString(map);
        //3. ws推送消息到客户端
        webSocketServer.sendToAllClient(json);
        //===================================通知商家: 新订单来了===========================//
    }

    // 历史订单
    @Override
    public PageBean<OrderVO> findByPage(OrdersPageQueryDTO dto) {
        //1. 开启分页
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        //2. 条件查询
        List<OrderVO> list = ordersMapper.findList(dto);
        Page<OrderVO> page = (Page<OrderVO>) list;
        //3. 遍历订单集合，封装明细
        page.getResult().stream().forEach(orderVO -> {
            //3-1 查询订单明细
            List<OrderDetail> detailList = orderDetailMapper.findByOrderId(orderVO.getId());
            //3-2 封装到vo
            orderVO.setOrderDetailList(detailList);
            //3-3 订单明细封装字符串格式
            StringBuilder sb = new StringBuilder();
            detailList.stream().forEach(detail -> {
                sb.append(detail.getName()).append("x").append(detail.getNumber()).append(";");
            });
            orderVO.setOrderDishes(sb.toString());
        });
        //4. 返回
        return new PageBean<>(page.getTotal(), page.getResult());
    }

    // 订单详情
    @Override
    public OrderVO findByOrderId(Long id) {
        //1. 根据订单id查询基本信息
        OrderVO orderVO = ordersMapper.findById(id);
        //2. 查询订单明细
        if (orderVO != null) {
            List<OrderDetail> detailList = orderDetailMapper.findByOrderId(id);
            orderVO.setOrderDetailList(detailList);
        }
        //3. 封装并返回vo
        return orderVO;
    }

    // 取消订单
    @Override
    public void cancel(Long id)throws Exception {
        //1. 根据订单id查询基本信息
        OrderVO orderVO = ordersMapper.findById(id);
        //2. 判断状态
        if (orderVO.getStatus()>2) {// 3 已接单 4 派送中 5 已完成 6 已取消 =》 不允许用户取消订单
            throw new BusinessException("请联系商家取消");
        }
        //3. 修改订单状态
        //3-1 基本信息
        Orders orders = new Orders();
        orders.setId(id);// 订单id
        orders.setStatus(6);// 订单状态：已取消
        orders.setCancelReason("用户取消");// 取消原因
        orders.setCancelTime(LocalDateTime.now());// 取消时间
        //3-2 如果状态为已付款，需要退款
        if (orderVO.getStatus()==2) {
            // 你们课下这步省略
            weChatPayUtil.refund(orderVO.getNumber(),orderVO.getNumber(),new BigDecimal(0.01),new BigDecimal(0.01));
            orders.setPayStatus(2);// 支付状态：已退款
        }
        //3-3 mapper修改订单
        ordersMapper.update(orders);

    }

    // 再来一单
    @Override
    public void repetition(Long id) {
        //1. 清理购物车
        shoppingCartService.clean();
        //2. 查询订单明细
        List<OrderDetail> orderDetailList = orderDetailMapper.findByOrderId(id);
        //3. 遍历订单明细，添加到购物车
        orderDetailList.stream().forEach(orderDetail -> {
            //3-1 拷贝购物项
            ShoppingCart shoppingCart = BeanUtil.copyProperties(orderDetail, ShoppingCart.class, "id");
            //3-2 填充信息
            shoppingCart.setUserId(UserHolder.get());
            shoppingCart.setCreateTime(LocalDateTime.now());
            //3-3 添加到购物车
            shoppingCartMapper.save(shoppingCart);
        });

    }

    // 统计各个状态的订单数量
    @Override
    public OrderStatisticsVO statistics() {
        // 查询待接单数量 2
        Integer toBeConfirmed = ordersMapper.findCountStatus(2);
        // 查询待派送数量 3
        Integer confirmed = ordersMapper.findCountStatus(3);
        // 查询配送中数量 4
        Integer deliveryInProgress = ordersMapper.findCountStatus(4);
        // 封装并返回vo
        return OrderStatisticsVO.builder()
                .toBeConfirmed(toBeConfirmed)
                .confirmed(confirmed)
                .deliveryInProgress(deliveryInProgress)
                .build();
    }

    // 接单
    @Override
    public void confirm(OrdersConfirmDTO dto) {
        //1. 查询订单信息
        OrderVO orderVO = ordersMapper.findById(dto.getId());
        //2. 校验状态是否合法
        if (orderVO.getStatus() != 2) {
            throw new BusinessException("订单状态不合法");
        }
        //3. 修改订单状态
        Orders orders = Orders.builder()
                .id(dto.getId())
                .status(3)// 订单状态：已接单
                .build();
        ordersMapper.update(orders);
    }

    // 拒单
    @Override
    public void rejection(OrdersRejectionDTO dto) {
        //1. 查询订单信息
        OrderVO orderVO = ordersMapper.findById(dto.getId());
        //2. 校验状态是否合法
        if (orderVO.getStatus() != 2) {
            throw new BusinessException("订单状态不合法");
        }
        //3. 修改订单状态
        Orders orders = Orders.builder()
                .id(dto.getId())
                .status(6)// 订单状态：已取消
                .cancelReason("商家拒单")
                .rejectionReason(dto.getRejectionReason())// 拒绝原因
                .cancelTime(LocalDateTime.now())// 取消时间
                .build();
        //4. 判断用户是否已付款
        if (orderVO.getPayStatus() == 1) {
            //4-1 退款
            try {
                weChatPayUtil.refund(orderVO.getNumber(),orderVO.getNumber(),new BigDecimal(0.01),new BigDecimal(0.01));
            } catch (Exception exception) {
               throw  new BusinessException("退款失败，请联系商家");
            }
            //4-2 修改支付状态
            orders.setPayStatus(2);// 支付状态：已退款
        }

        ordersMapper.update(orders);
    }

    // 用户催单
    @Override
    public void reminder(Long id) {
        //===================================通知商家: 催单===========================//
        // 查询数据库
        OrderVO ordersDB = ordersMapper.findById(id);

        //1. 准备消息内容
        Map<String,Object> map = new HashMap<>();
        map.put("type",2);
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号：" + ordersDB.getNumber());
        //2. 转json
        String json = JSON.toJSONString(map);
        //3. ws推送消息到客户端
        webSocketServer.sendToAllClient(json);
        //===================================通知商家: 催单===========================//
    }

    //后台取消订单
    @Override
    public void cancelByAdmin(OrdersCancelDTO dto) {
        // 查询订单信息
        OrderVO orderVO = ordersMapper.findById(dto.getId());
        // 判断订单状态是否正确
        if (orderVO.getStatus() == Orders.COMPLETED || orderVO.getStatus() == Orders.CANCELLED) {
            throw new BusinessException("订单状态不正确");
        }
        // 退款
        if (orderVO.getPayStatus() == Orders.PAID) {
            orderVO.setPayStatus(Orders.REFUND);
        }
        // 修改订单
        orderVO.setStatus(Orders.CANCELLED);
        orderVO.setCancelReason(dto.getCancelReason());
        orderVO.setCancelTime(LocalDateTime.now());
        ordersMapper.update(orderVO);
    }

    //派送订单
    @Override
    public void delivery(Long id) {
        //查询订单信息
        OrderVO orderVO = ordersMapper.findById(id);
        //判断订单状态
        if (orderVO.getStatus() != Orders.CONFIRMED) {
            throw new BusinessException("订单状态不正确");
        }
        //修改订单状态
        orderVO.setStatus(Orders.DELIVERY_IN_PROGRESS);
        ordersMapper.update(orderVO);
    }

    //订单完成
    @Override
    public void complete(Long id) {
        //查询订单信息
        OrderVO orderVO = ordersMapper.findById(id);
        //判断订单状态
        if (orderVO.getStatus() != Orders.DELIVERY_IN_PROGRESS) {
            throw new BusinessException("订单状态不正确");
        }
        //修改订单状态
        orderVO.setStatus(Orders.COMPLETED);
        orderVO.setDeliveryTime(LocalDateTime.now());
        ordersMapper.update(orderVO);
    }
}
